<!-- 方案排斥 -->
<template>
    <el-drawer v-loading="drawerLoading" :model-value="modelValue" :close-on-click-modal="false" :size="600"
        class="repel-dialog" title="单个上传" @closed="handleClose" @opened="handleOpen">
        <div class="my-form">
            <el-form ref="formRef" :model="repelForm" :inline="true" class="repel-form" name="repelForm"
                :rules="perUploadPhtRules">
                <el-form-item label="" prop="city">
                    <div class="form-item-title">城市<i>*</i></div>
                    <el-select v-model="repelForm.city" placeholder="请选择" @change="(val: any) => getPlanList()">
                        <el-option v-for="item in cityList" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="" prop="beginDate">
                    <div class="form-item-title">投放开始日期<i>*</i></div>
                    <el-date-picker v-model="repelForm.beginDate" value-format="YYYY-MM-DD"
                        @change="(val: any) => getPlanList()"></el-date-picker>
                </el-form-item>
                <el-form-item label="" prop="planId">
                    <div class="form-item-title">方案名称<i>*</i></div>
                    <el-select v-model="repelForm.planId" filterable placeholder="请选择"
                        @input="(val: any) => searchList(val)">
                        <el-option v-for="item in planList" :key="item.planId" :label="item.planName" :value="item.planId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="" prop="imgType">
                    <div class="form-item-title">监拍类型<i>*</i></div>
                    <el-select v-model="repelForm.imgType" placeholder="请选择">
                        <el-option label="上刊" :value="1" />
                        <el-option label="上刊" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="" prop="machineNum">
                    <div class="form-item-title">点位编码<i>*</i></div>
                    <el-input v-model.trim="repelForm.machineNum" placeholder="请输入" clearable></el-input>
                </el-form-item>
                <el-form-item class="pht-form-item" label="" prop="isWithPht">
                    <div class="form-item-title">夹报照片<i>*</i></div>
                    <el-radio-group v-model="repelForm.clip">
                        <el-radio :label="1" size="large">是</el-radio>
                        <el-radio :label="2" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div class="upload">
                <div class="t form-item-title">刊播照片<i>*</i></div>
                <xc-upload accept=".jpg" :limit="1" :max-size="1" class="upload-btn" :limit-type="{ types: ['jpg'] }"
                    :http-request="(file: File) => uploadFile(file)" tip="只支持jpg,照片大小不超过1M" @remove="removeFile"
                    :key="uploadKey"></xc-upload>
                <!-- {{uploadSuccess?1:0}} -->
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button plain class="cancel" @click="handleClose"> 取 消 </el-button>
                <el-button :loading="drawerLoading" type="primary" @click="submits"> 确定 </el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, computed } from 'vue';
import { Upload } from '@x-tech/fe-puma-lib-upload';
import xcUpload from '@x-tech/fe-pc-components/src/components/XcUpload/index.vue';
import XCMessageMgr from '@/utils/XCMessageMgr';
import { useStore } from 'vuex';
import { perUploadPhtRules } from './rules'
import { getNearEstDate } from '@/utils/common';
import { getPlanListSelector, uploadPhoto } from '@/api/plan';
const emits = defineEmits<{ (e: 'update:modelValue', visible: boolean): void; (e: 'success'): void }>();
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false,
    },
    mediaType: {
        type: Object,
        default: () => 1,
    },
});

const store = useStore();
const cityListState = computed<{ city: string, cityCode: string | number }[]>(() => store.state.userGroup.userInfo?.cityList);
const cityList = computed(() => cityListState.value.map(item => ({
    label: item.city,
    value: item.cityCode
})))
const drawerLoading = ref(false);
const repelForm = reactive({
    city: cityList.value[0]?.value,
    beginDate: getNearEstDate(),
    planId: '',
    imgType: 1,
    machineNum: '',
    clip: 1, // 是否夹照
});

//防抖搜索
let timer: NodeJS.Timeout | string | number | undefined | null = null;
function searchList(val: any) {
    if (timer) {
        clearTimeout(timer);
    }
    console.log("val", val);
    timer = setTimeout(() => {
        getPlanList(val.target.value.trim());
    }, 400);
}

const planList = ref<any>([]);
async function getPlanList(planName = '') {
    const params = {
        mediaType: props.mediaType,
        //当输入了名字 根据名字模糊搜索
        planName,
        city: repelForm.city,
        pageSize: 100,
        pageNum: 1
    }
    const res = await getPlanListSelector(params);
    console.log(res);
    if (res.list.length >= 100) {
        planList.value = res.list.slice(0, 100);
    }
    else {
        planList.value = res.list;
    }
}

let uploadFileUrl = ref<string>('');
const upl = new Upload(window.XCConfig.VUE_APP_ENV);
const uploadSuccess = ref(false);
const uploadKey = ref(0);
const formRef = ref<any>(null);

const resetForm = () => {
    console.log('formRef', formRef.value);
    formRef.value?.resetFields();
    uploadFileUrl.value = '';
    uploadKey.value++;
    uploadSuccess.value = false;
};

const handleClose = () => {
    emits('update:modelValue', false);
    resetForm();
};

const handleOpen = () => {
    getPlanList();
};

const uploadFile = async (file: File) => {
    uploadSuccess.value = false;  //代表有文件上传
    let _file: any = file;
    if (Array.isArray(file) && file.length) {
        _file = file[0];
    }
    console.log('file:', file);
    const res = await upl.uploadWithoutFilename(_file.file!, false);
    console.log(res);
    uploadFileUrl.value = res;

    // XCMessageMgr.Instance.showMessageSuc('上传成功');
    console.log(uploadFileUrl.value);
    uploadSuccess.value = true;
};
function removeFile(f: any) {
    uploadSuccess.value = false;
    uploadFileUrl.value = '';
};

async function submits() {
    const isValid = await formRef.value.validate();
    if (!isValid) return;
    if (!uploadFileUrl.value) {
        XCMessageMgr.Instance.showMessageError('请选择照片');
        return;
    }
    const params = {
        ...repelForm,
        imgPath: uploadFileUrl.value,
        systemType: props.mediaType
    }
    drawerLoading.value = true;
    try {
        await uploadPhoto(params);
        XCMessageMgr.Instance.showMessageSuc('上传成功');
        resetForm();
    } catch (error) {
        
    }finally {
        drawerLoading.value = false;  
    }
}
</script>

<style lang="scss" scoped>
.form-item-title {
    width: 260px;
    display: flex;
    align-items: center;
    height: 30px;
    font-size: 14px;

    i {
        display: inline-block;
        color: #F00000;
        margin-top: 3px;
        margin-left: 2px;
    }
}

.el-form-item {
    width: 260px;
    // background-color: pink;
    margin: 0;
}

.el-form-item:nth-child(2n+1) {
    margin-right: 20px;
}

::v-deep .el-input {
    display: inline-block;
    width: 260px !important;
}

.upload {
    margin-top: -5px;

    .t {
        margin-bottom: 5px;
    }
}

.my-form {
    // margin-top: -30px;
}
</style>
